package br.com.fixtrader.quoteserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class MulticastProducer {
	
	private Map<String,String> adresses;
	private MulticastSocket multicastSocket;
	private int usedAdresses;
	
	public MulticastProducer() {
		usedAdresses = 1;
		adresses = new HashMap<String, String>();
		try {
			multicastSocket = new MulticastSocket(7777);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String addPaper(String paper) {
		String adress = null;
		int pre = usedAdresses % 254;
		int suf = usedAdresses;
		adress = "224.1."+pre+"."+suf;
		try {
			multicastSocket.joinGroup(InetAddress.getByName(adress));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		adresses.put(paper, adress);
		usedAdresses++;
		return adress;
	}
	
	public String getAdress(String paper) {
		return adresses.get(paper);
	}

	public void sendMessage(String paper, String message) {
		byte[] b = message.getBytes();
		try {
			DatagramPacket dgram = new DatagramPacket(b, b.length, InetAddress
					.getByName(adresses.get(paper)), 7777);
			System.out.println(dgram.getAddress().getHostName());
			multicastSocket.send(dgram);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
